package com.xbk.seckill.application.message;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xbk.seckill.application.service.SeckillGoodsService;
import com.xbk.seckill.common.constants.SeckillConstants;
import com.xbk.seckill.common.model.message.TxMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 商品微服务事务消息
 *
 * @author xiexu
 * @date 2025/2/26 20:55
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = SeckillConstants.TX_GOODS_CONSUMER_GROUP, topic = SeckillConstants.TOPIC_TX_MSG)
public class GoodsTxMessageListener implements RocketMQListener<String> {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    /**
     * 当事务消息被提交后，rocketmq会执行该方法
     *
     * @param message
     */
    @Override
    public void onMessage(String message) {
        if (StrUtil.isEmpty(message)) {
            return;
        }
        log.info("秒杀商品微服务开始消费事务消息:{}", message);
        // 构建事务消息实体
        TxMessage txMessage = this.getTxMessage(message);
        // 如果异常信息字段为false，则表示订单微服务没有抛出异常，需要扣减数据库库存信息
        if (BooleanUtil.isFalse(txMessage.getException())) {
            // 扣减数据库库存
            seckillGoodsService.updateAvailableStock(txMessage);
        }
    }

    /**
     * 获取事务消息
     *
     * @param msg
     * @return
     */
    private TxMessage getTxMessage(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String txStr = jsonObject.getString(SeckillConstants.MSG_KEY);
        return JSONObject.parseObject(txStr, TxMessage.class);
    }
}
